// ol
import { Map, View } from "ol";
import { defaults } from "ol/control";
import { defaults as interactionDefaults } from "ol/interaction";
import { fromLonLat } from "ol/proj";
import { Stroke } from 'ol/style.js';
import Graticule from 'ol/layer/Graticule';
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import ScaleLine from 'ol/control/ScaleLine';

const tdtKey = "16d5f71cd95def36fea5d2d45d9592f8"

export default {
  // 初始化海图
  initMap: function (MapConfig) {
    var mview = new View({
      projection: MapConfig.EPSGCode,
      center: fromLonLat(MapConfig.center),
      zoom: MapConfig.zoom,
      maxZoom: MapConfig.mapZIndexLimit[1],
      minZoom: MapConfig.mapZIndexLimit[0],
      constrainResolution: true,
    });
    return new Map({
      controls: defaults({
        attribution: false,
        zoom: false,
        rotate: false,
      }).extend([]),
      target: MapConfig.target,
      layers: [this.initBaseLayer()],
      view: mview,
      interactions: new interactionDefaults({
        doubleClickZoom: false, // 屏蔽双击放大事件
      }),
    });
  },
  // 初始化网格
  initGraticule: function (map) {
    new Graticule({
      map: map,
      strokeStyle: new Stroke({
        color: 'rgba(12, 12, 12, 0.6)',
        width: 0.4,
        lineDash: [10, 10],
      }),
      targetSize: 150,
      opacity: 0.6,
      zIndex: 201,
      showLabels: true,
    });
  },
  initScaleLine: function (map) {
    // 添加比例尺控件
    const scaleLineControl = new ScaleLine({
      units: 'metric', // 选择 'metric'（米）或 'imperial'（英里）
      minWidth: 50, // 最小宽度
    });
    map.addControl(scaleLineControl);
  },
  // 渲染地图
  initBaseLayer: function () {
    const url = import.meta.env.VITE_APP_MAP
    // 基础海图
    let source = new XYZ(
      {
        url
      }
    );
    let layer = new TileLayer({
      source: source,
      name: "baseMap",
      zIndex: 200
    });
    return layer
  },
}